#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "log.hpp"

Log lg;
const int size = 4096;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " port ip" << std::endl;
}

int main(int argc, char *argv[])
{
    // ./UdpClient port ip
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        lg(FATAL, "socket fail, errno: %d, strerror: %s", errno, strerror(errno));
        exit(0);
    }
    lg(INFO, "socket success, sockfd: %d, errno: %d, strerror: %s", sockfd, errno, strerror(errno));

    struct sockaddr_in Server;
    bzero(&Server, sizeof(Server));
    Server.sin_family = AF_INET;
    Server.sin_port = htons(stoi(argv[1]));
    Server.sin_addr.s_addr = inet_addr(argv[2]);
    socklen_t len = sizeof(Server); 

    char buffer[size];
    std::string message;

    while(true)
    {
        std::cout << "Client Say@ ";
        getline(std::cin, message);
        // 我们在聊天室进行多人聊天时每个人，就算我不发消息我也是可以收到别人的消息的，但是以下单进程是是做不到的
        // 单线程，如果键盘资源没就绪，该进程就会处于阻塞状态，执行不了后续的代码，你就收不到后续别人发送的信息了
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&Server, len);

        struct sockaddr Client;
        socklen_t len = sizeof(Client);
        ssize_t s = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&Client, &len);
        if(s > 0)
        {
            buffer[s] = 0;
            // std::cout << buffer << std::endl;
        }
    }

    close(sockfd);

    return 0;
}